const { DataTypes, Model } = require('sequelize');
const { sequelize } = require('../config/database');

class Pet extends Model {
  // 添加照片
  async addPhoto(photoData) {
    const photos = this.photos || [];
    const isFirstPhoto = photos.length === 0;
    photos.push({
      ...photoData,
      isPrimary: isFirstPhoto,
      uploadedAt: new Date()
    });
    this.photos = photos;
    return this.save();
  }

  // 设置主要照片
  async setPrimaryPhoto(photoIndex) {
    const photos = this.photos || [];
    photos.forEach((photo, index) => {
      photo.isPrimary = index === photoIndex;
    });
    this.photos = photos;
    return this.save();
  }

  // 删除照片
  async removePhoto(photoIndex) {
    const photos = this.photos || [];
    if (photoIndex < 0 || photoIndex >= photos.length) {
      throw new Error('照片不存在');
    }
    
    const wasPrimary = photos[photoIndex].isPrimary;
    photos.splice(photoIndex, 1);
    
    // 如果删除的是主要照片，设置第一张为主要照片
    if (wasPrimary && photos.length > 0) {
      photos[0].isPrimary = true;
    }
    
    this.photos = photos;
    return this.save();
  }

  // 更新统计信息
  async updateStats(orderCompleted = false, rating = null) {
    const stats = this.stats || { totalCareOrders: 0, completedCareOrders: 0, averageRating: 0, ratingCount: 0 };
    
    stats.totalCareOrders += 1;
    
    if (orderCompleted) {
      stats.completedCareOrders += 1;
    }
    
    if (rating !== null) {
      const currentTotal = stats.averageRating * stats.ratingCount;
      stats.ratingCount += 1;
      stats.averageRating = (currentTotal + rating) / stats.ratingCount;
    }
    
    this.stats = stats;
    return this.save({ validate: false });
  }

  // 虚拟字段: 年龄（月）
  get ageInMonths() {
    if (this.dateOfBirth) {
      const now = new Date();
      const birth = new Date(this.dateOfBirth);
      const diffTime = Math.abs(now - birth);
      const diffMonths = Math.ceil(diffTime / (1000 * 60 * 60 * 24 * 30.44));
      return diffMonths;
    }
    const age = this.age || {};
    if (age.years !== undefined && age.months !== undefined) {
      return age.years * 12 + age.months;
    }
    return null;
  }

  // 虚拟字段: 主要照片
  get primaryPhoto() {
    const photos = this.photos || [];
    const primary = photos.find(photo => photo.isPrimary);
    return primary ? primary.url : (photos.length > 0 ? photos[0].url : null);
  }

  // 虚拟字段: 疫苗是否到期
  get isVaccinationDue() {
    const health = this.health || {};
    const records = health.vaccinationRecords || [];
    if (records.length === 0) return true;
    
    const now = new Date();
    return records.some(record => 
      record.nextDue && new Date(record.nextDue) <= now
    );
  }
}

Pet.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  // 基本信息
  name: {
    type: DataTypes.STRING(50),
    allowNull: false
  },
  species: {
    type: DataTypes.ENUM('dog', 'cat', 'bird', 'fish', 'rabbit', 'hamster', 'turtle', 'other'),
    allowNull: false
  },
  breed: {
    type: DataTypes.STRING(100)
  },
  gender: {
    type: DataTypes.ENUM('male', 'female', 'unknown'),
    defaultValue: 'unknown'
  },
  
  // 年龄信息
  dateOfBirth: {
    type: DataTypes.DATE,
    validate: {
      isBeforeToday(value) {
        if (value && value > new Date()) {
          throw new Error('出生日期不能是未来的日期');
        }
      }
    }
  },
  age: {
    type: DataTypes.JSON,
    defaultValue: {}
  },
  
  // 外观特征
  color: {
    type: DataTypes.STRING(100)
  },
  size: {
    type: DataTypes.ENUM('tiny', 'small', 'medium', 'large', 'giant'),
    allowNull: false
  },
  weight: {
    type: DataTypes.DECIMAL(5, 2),
    validate: {
      min: 0.1,
      max: 200
    }
  },
  
  // 照片 (JSON)
  photos: {
    type: DataTypes.JSON,
    defaultValue: []
  },
  
  // 健康信息 (JSON)
  health: {
    type: DataTypes.JSON,
    defaultValue: {
      vaccinated: false,
      vaccinationRecords: [],
      spayedNeutered: false,
      allergies: [],
      medications: [],
      medicalConditions: []
    }
  },
  
  // 行为特征 (JSON)
  behavior: {
    type: DataTypes.JSON,
    defaultValue: {
      temperament: [],
      goodWithKids: true,
      goodWithOtherPets: true,
      activityLevel: 'moderate',
      specialNeeds: []
    }
  },
  
  // 喂养信息 (JSON)
  feeding: {
    type: DataTypes.JSON,
    defaultValue: {
      diet: 'dry',
      feedingSchedule: [],
      treats: []
    }
  },
  
  // 护理需求 (JSON)
  careRequirements: {
    type: DataTypes.JSON,
    defaultValue: {
      exerciseNeeds: 'moderate',
      groomingNeeds: 'moderate',
      socialNeeds: 'moderate'
    }
  },
  
  // 紧急联系信息 (JSON)
  emergencyContact: {
    type: DataTypes.JSON,
    defaultValue: {}
  },
  
  // 所有者ID
  ownerId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: 'users',
      key: 'id'
    }
  },
  
  // 状态
  status: {
    type: DataTypes.ENUM('active', 'inactive', 'lost', 'deceased'),
    defaultValue: 'active'
  },
  
  // 可用性 (JSON)
  availability: {
    type: DataTypes.JSON,
    defaultValue: {
      needsCare: false,
      preferredCaregivers: [],
      blacklistedCaregivers: []
    }
  },
  
  // 统计信息 (JSON)
  stats: {
    type: DataTypes.JSON,
    defaultValue: {
      totalCareOrders: 0,
      completedCareOrders: 0,
      averageRating: 0,
      ratingCount: 0
    }
  }
}, {
  sequelize,
  modelName: 'Pet',
  tableName: 'pets',
  timestamps: true,
  indexes: [
    { fields: ['ownerId'] },
    { fields: ['species'] },
    { fields: ['status'] }
  ]
});

module.exports = Pet;